package com.hxd.otc.module.order.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.SingBlocksDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.order.adapter.AdOrderDetailAlipayAdapter;
import com.hxd.otc.module.order.adapter.AdOrderDetailBankAdapter;
import com.hxd.otc.module.order.bean.AdOrderDetailBean;
import com.hxd.otc.module.order.contract.AdSaleOrderDetailContract;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.module.order.presenter.AdSaleOrderDetailPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.CountDownUtils;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.GlideUtils;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.widget.BlocksToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;


/**
 * 包  名 :  com.hxd.otc.module.order
 * 类  名 : SaleOrderDetailActivity
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${}广告商 卖出 订单详情页
 */
public class AdSaleOrderDetailActivity extends PermissionActivity<AdSaleOrderDetailPresenter> implements AdSaleOrderDetailContract.View {

    @BindView(R.id.bt_right1)
    Button btRight1;

    @BindView(R.id.bt_right2)
    Button btRight2;

    @BindView(R.id.iv_head)
    CircleImageView ivHead;

    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;

    @BindView(R.id.tv_account)
    TextView tvAccount;

    @BindView(R.id.tv_pay_state)
    TextView tvPayState;

    @BindView(R.id.tv_time)
    TextView tvTime;

    @BindView(R.id.tv_red)
    TextView tvRed;

    @BindView(R.id.tv_price)
    TextView tvPrice;

    @BindView(R.id.tv_number)
    TextView tvNumber;

    @BindView(R.id.tv_other_name)
    TextView tvOrtherName;

    @BindView(R.id.ll_pay_infom)
    LinearLayout llPayInfom;

    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    @BindView(R.id.ll_all)
    LinearLayout llAll;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.rc_alipay)
    RecyclerView rcAlipay;

    @BindView(R.id.rc_bank)
    RecyclerView rcBank;

    @BindView(R.id.tb_cancled)
    TextView tbCancled;
    /**
     * 订单卖出状态
     * //0.未支付，1，已付款，2.申诉中，3.已取消，4.完成 ,
     */
    public static final int SALE_UNPAID = 0;//未付款
    public static final int SALE_PAYED = 1;//已付款
    public static final int SALE_REPRESENTATION = 2;//申诉中
    public static final int SALE_CANCLED = 3;//已取消
    public static final int SALE_FINISHED = 4;//已完成

    public static final int SALE_PAYED_REQUEST = 123;//申诉 requestCode

    public static final int CONFIRM_PAYMENT_SUCCESS = 3;//确认收款操作成功
    public static final int WITHDRAW_SUCCESS = 5;//撤回申诉成功

    public static String[] EXTERNAL_PERMISSION = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    AdOrderDetailBean orderBean;

    MultipleBlocksDialog callDailog;
    MultipleBlocksDialog withdrawDailog;
    MultipleBlocksDialog confirmDailog;

    SingBlocksDialog copyDialog;

    boolean isWithdraw = true;//是撤回申诉状态，还是联系客服状态

    AdOrderDetailAlipayAdapter alipayAdapter;
    AdOrderDetailBankAdapter bankAdapter;

    Disposable mDisposable;

    String orderId;
    boolean isFrist = true;//
    int statue = -1;//记录订单状态是否改变
    boolean isRefreshRedMess;//刷新融云消息

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ad_sale_order_detail;
    }

    @Override
    protected void initView() {
        orderId = getIntent().getExtras().getString(AllOrderFragment.ORDER_ID);

        rcAlipay.setLayoutManager(new LinearLayoutManager(this));
        alipayAdapter = new AdOrderDetailAlipayAdapter(this);
        rcAlipay.setAdapter(alipayAdapter);
        rcAlipay.setNestedScrollingEnabled(false);


        rcBank.setLayoutManager(new LinearLayoutManager(this));
        bankAdapter = new AdOrderDetailBankAdapter();
        rcBank.setAdapter(bankAdapter);
        rcBank.setNestedScrollingEnabled(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadData(orderId);
            }
        });

        alipayAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("alipayAddress", alipayAdapter.getData().get(position).alipayAddress);
                $startActivity(AlipayQRcodeActivity.class, bundle);
            }
        });
        bankAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                copyData(bankAdapter.getData().get(position).bankNo);
            }
        });

    }

    @Override
    protected void initData() {

        refreshLayout.autoRefresh(0, 10, 1);
    }

    @Override
    public void onSetData(AdOrderDetailBean bean) {
        orderBean = bean;
        if (isFrist) {
            statue = orderBean.orderVo.status;
            isFrist = false;
            if (orderBean.orderVo.status == 0 || orderBean.orderVo.status == 1 || orderBean.orderVo.status == 2)
                getRongUnreadCount();
        }
        refreshData();

        if (bean.payInfoVo.alipayInfoPos != null && bean.payInfoVo.alipayInfoPos.size() > 0 && bean.payInfoVo.alipayInfoPos.get(0) != null) {
            if (bean.payInfoVo.alipayInfoPos.size() > 5) {
                bean.payInfoVo.alipayInfoPos = bean.payInfoVo.alipayInfoPos.subList(0, 1);
            }
            alipayAdapter.setNewData(bean.payInfoVo.alipayInfoPos);
        }

        if (bean.payInfoVo.bankInfoPos != null && bean.payInfoVo.bankInfoPos.size() > 0 && bean.payInfoVo.bankInfoPos.get(0) != null) {
            if (bean.payInfoVo.bankInfoPos.size() > 5) {
                bean.payInfoVo.bankInfoPos = bean.payInfoVo.bankInfoPos.subList(0, 5);
            }
            bankAdapter.setNewData(bean.payInfoVo.bankInfoPos);
        }
    }

    @Override
    public void refreshView(int type) {//根据不同操作，刷新View
        setResult(RESULT_OK);
        switch (type) {
            case CONFIRM_PAYMENT_SUCCESS:
                if (mDisposable != null && !mDisposable.isDisposed()) {
                    mDisposable.dispose();
                }
                postSticky(new Event.RefreshOrderRedEvent(statue,false));//确认收款的 订单状态一定是发生变化的,通知更新红点
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDER_ID, orderBean.orderVo.id);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, false);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
            case WITHDRAW_SUCCESS:
                //当撤回申诉后， 订单变为已付款状态
                mPresenter.doLoadData(orderId);
                break;
        }
    }

    /**
     * 获取融云未读消息数
     */
    private void getRongUnreadCount() {
        RongIMClient.getInstance().getUnreadCount(Conversation.ConversationType.PRIVATE, orderBean.buyVo.id, new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                if (integer != null && integer > 0) {
                    tvRed.setVisibility(View.VISIBLE);
                    tvRed.setText(String.valueOf(integer));
                } else {
                    tvRed.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    @Override
    public void onHideLoading() {
        super.onHideLoading();
        refreshLayout.finishRefresh();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected AdSaleOrderDetailPresenter createPresenter() {
        return new AdSaleOrderDetailPresenter(this);
    }

    @Override
    protected void initPermissions() {
        super.initPermissions();
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }

        llAll.setVisibility(View.VISIBLE);
        tvName.setText(orderBean.buyVo.nickName);
        GlideUtils.loadHeadImageView(this, orderBean.buyVo.avatar, ivHead,
                R.mipmap.order_head_portrait_img, R.mipmap.order_head_portrait_img);
        tvOrderNumber.setText(orderBean.orderVo.orderNo);
        tvAccount.setText(getString(R.string.deal_account, StringUtil.format2Number(orderBean.orderVo.money), orderBean.orderVo.legalCurrency));

        String[] split = orderBean.orderVo.transactionPair.split("/");
        if (split.length > 1) {
            tvNumber.setText(getResources().getString(R.string.number_detail, StringUtil.format2Number(orderBean.orderVo.quantity), split[0]));
            tvPrice.setText(getResources().getString(R.string.price_detail,
                    StringUtil.format2Number(orderBean.orderVo.unitPrice), orderBean.orderVo.legalCurrency + "/" + split[0]));
        }
        switch (orderBean.orderVo.status) {
            case SALE_UNPAID://未付款 只有 拨打电话界面
                llBottom.setVisibility(View.VISIBLE);
                tvOrtherName.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFC807B));
                tvPayState.setText(getResources().getString(R.string.order_un_pay));
                btRight1.setVisibility(View.GONE);
                btRight2.setVisibility(View.GONE);

                tvTime.setTextColor(getResources().getColor(R.color.color_FFFC807B));
                tvTime.setVisibility(View.VISIBLE);
                interval((int) DateUtil.getunPayCountdown(orderBean.orderVo.currentTime, orderBean.orderVo.createTime, orderBean.orderVo.sellNoPayTimeOut,DateUtil.YY_MM_DD_HH_MM_SS));
                break;
            case SALE_PAYED://已付款
                llBottom.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvPayState.setText(getResources().getString(R.string.order_pay));
                tvOrtherName.setVisibility(View.VISIBLE);
                tvOrtherName.setText(getString(R.string.payment_party_name, orderBean.buyVo.name));

                btRight1.setVisibility(View.VISIBLE);
                btRight1.setText(getString(R.string.confirm_receipt));
                btRight1.setBackgroundColor(getResources().getColor(R.color.color_FFD2A56B));
                btRight1.setTextColor(getResources().getColor(R.color.colorWhite));

                btRight2.setVisibility(View.VISIBLE);
                btRight2.setText(getString(R.string.representation));
                btRight2.setBackgroundColor(getResources().getColor(R.color.color_FF3B3B55));
                btRight2.setTextColor(getResources().getColor(R.color.colorWhite));

                tvTime.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvTime.setVisibility(View.VISIBLE);
                interval((int) DateUtil.getPayedCountdown(orderBean.orderVo.currentTime, orderBean.orderVo.createTime, DateUtil.YY_MM_DD_HH_MM_SS));
                break;
            case SALE_REPRESENTATION://申诉中
                tvTime.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                tvOrtherName.setVisibility(View.VISIBLE);
                tvOrtherName.setText(getString(R.string.payment_party_name, orderBean.buyVo.name));
                btRight1.setVisibility(View.GONE);
                btRight2.setVisibility(View.VISIBLE);
                if (orderBean.orderVo.whoAppeal == 1) {//自己发起的申诉
                    btRight2.setText(getString(R.string.withdraw_representation));
                    btRight2.setBackgroundColor(getResources().getColor(R.color.color_FF3B3B55));
                    tvPayState.setText(getResources().getString(R.string.your_appeal));
                } else {//对方发起
                    btRight2.setText(getString(R.string.contact_platform));
                    tvPayState.setText(getResources().getString(R.string.the_orther_appeal));
                    btRight2.setTextColor(getResources().getColor(R.color.color_FF516168));
                    btRight2.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                }
                break;
            case SALE_CANCLED://已取消
                tbCancled.setVisibility(View.VISIBLE);
                llPayInfom.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvPayState.setText(getResources().getString(R.string.order_cancle));
                btRight2.setBackgroundColor(getResources().getColor(R.color.color_FF95A2AC));
                break;
            case SALE_FINISHED:
                $setResult();
                refreshOrder();
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDER_ID, orderBean.orderVo.id);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, false);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
        }
    }

    /**
     * 未付款和已付款倒计时款操作
     */
    public void interval(int count) {
        CountDownUtils.interval(count / 1000, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                tvTime.setText(DateUtil.getTimeMinutesSecond(along));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //当倒计时完成，则需要请求订单详情接口，刷新数据，取消订单
                mPresenter.doLoadData(orderId);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRefreshRedMess) {
            getRongUnreadCount();
            isRefreshRedMess = false;
        }
    }

    @OnClick({R.id.rl_contact, R.id.bt_call, R.id.bt_right2, R.id.bt_right1, R.id.back_tv})
    public void onCliekEvent(View view) {
        switch (view.getId()) {
            case R.id.back_tv:
                refreshOrder();
                finish();
                break;
            case R.id.rl_contact: //联系对方
                isRefreshRedMess = true;
                RongIM.getInstance().startConversation(this, Conversation.ConversationType.PRIVATE, orderBean.buyVo.id, orderBean.buyVo.nickName);
                break;
            case R.id.bt_call://打电话
                call();
                break;
            case R.id.bt_right2:// 最右边按钮 的 左边按钮
                btRight2Click();
                break;
            case R.id.bt_right1:// z最右边的按钮
                btRight1Click();
                break;
        }
    }

    private void btRight1Click() {
        switch ((orderBean.orderVo.status)) {
            case SALE_UNPAID://未付款 ：没有状态

                break;
            case SALE_PAYED://已付款 状态---确认收款 按钮
                confirmClick();
                break;
            case SALE_REPRESENTATION://申诉中---没有状态

                break;

        }
    }

    private void btRight2Click() {
        switch (orderBean.orderVo.status) {
            case SALE_UNPAID:

                break;
            case SALE_PAYED://已付款 ----申诉按钮
                Bundle bundle = new Bundle();
                bundle.putString(AllOrderFragment.ORDER_ID, orderBean.orderVo.id);
                $startActivityForResult(ComplainActivity.class, bundle, SALE_PAYED_REQUEST);
                break;
            case SALE_REPRESENTATION://申诉中----是撤回申诉状态，还是联系客服状态（接入美洽客户就好了）

                if (orderBean.orderVo.whoAppeal == 1) {
                    withdrawClick();
                } else {
                    contractService();
                }
                break;
        }
    }

    private void copyData(String bankNo) {
        CommonUtil.copyData(bankNo);
        if (copyDialog == null)
            copyDialog = new SingBlocksDialog(this)
                    .setTitle(getString(R.string.copy_success))
                    .setGotText(getString(R.string.confirm), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            copyDialog.dismiss();
                        }
                    });

        copyDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SALE_PAYED_REQUEST) {
            refreshLayout.autoRefresh(0, 10, 1);
        }
    }

    private void call() {
        if (callDailog == null) {
            callDailog = new MultipleBlocksDialog(this)
                    .setContent(orderBean.buyVo.phone)
                    .setTitle(orderBean.buyVo.nickName)
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.dial), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callDailog.dismiss();
                            CommonUtil.callPhone(AdSaleOrderDetailActivity.this, orderBean.buyVo.phone);
                        }
                    });
        }
        callDailog.show();
    }


    /**
     * 撤回申诉操作
     */
    private void withdrawClick() {
        if (withdrawDailog == null)
            withdrawDailog = new MultipleBlocksDialog(this)
                    .setContent(getString(R.string.order_detail_withdraw_hint))
                    .setTitle(getString(R.string.withdraw_representation))
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.withdraw), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPresenter.withdrawalRep(orderBean.orderVo.id);
                            withdrawDailog.dismiss();
                        }
                    });

        withdrawDailog.show();
    }

    /**
     * 确认收款操作
     */
    private void confirmClick() {
        if (confirmDailog == null)
            confirmDailog = new MultipleBlocksDialog(this)
                    .setContent(getString(R.string.confirm_payment_content))
                    .setTitle(getString(R.string.confirm_receipt))
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.order_confirm), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPresenter.confirmPayment(orderBean.orderVo.id);
                            confirmDailog.dismiss();
                        }
                    });

        confirmDailog.show();
    }

    private void refreshOrder() {
        if (orderBean != null && orderBean.orderVo != null && statue != orderBean.orderVo.status)//订单状态发生改变时 通知更新红点
        {
            postSticky(new Event.RefreshOrderListEvent(statue,false));
        }
    }

    /**
     * 联系客服
     */
    private void contractService() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                goCustomService();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                BlocksToast.get().showToast(getResources().getString(R.string.meiqia_error));
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                BlocksToast.get().showToast(getResources().getString(R.string.meiqia_error));
            }

            @Override
            public void onLowVersion() {
                goCustomService();
            }
        }, EXTERNAL_PERMISSION);

    }

    private void goCustomService() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (callDailog != null)
            callDailog.onDestroy();
        callDailog = null;

        if (withdrawDailog != null)
            withdrawDailog.onDestroy();
        withdrawDailog = null;

        if (confirmDailog != null)
            confirmDailog.onDestroy();
        confirmDailog = null;

        if (mDisposable != null && !mDisposable.isDisposed())
            mDisposable.dispose();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        refreshOrder();

    }

}
